<template>
  <el-dialog :title="title"
             :visible.sync="visible"
             v-loading="loading"
             :before-close="modalClose"
             :close-on-click-modal="false"
             :close-on-press-escape="false"
             width="50%"
             append-to-body>
    <el-form ref="formRef"
             :model="formModel"
             :rules="formRules"
             label-width="120px">
      <el-form-item label="关联知识点："
                    prop="knowledge">
        <el-input v-model="formModel.knowledge"
                  placeholder="请填写关联知识点"
                  :autosize="{ minRows: 2, maxRows: 10}"
                  type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="对应图片："
                    prop="knowledgeImage">
        <el-upload multiple
                   :limit='6'
                   :action="imageUploadUrl"
                   accept=".JPG, .PNG, .JPEG,.jpg, .png, .jpeg"
                   list-type="picture-card"
                   :on-success="(response, file, fileList) => handlePictureCardPreview(response, file, fileList)"
                   :file-list='formModel.knowledgeImageList'
                   :on-remove='onremove'
                   :before-upload="beforeAvatarUpload">
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="关键词："
                    prop="keyWord">
        <el-input v-model="formModel.keyWord"
                  placeholder="请输入关键词"
                  class="w-200"
                  clearable></el-input>
        <el-button type="primary"
                   @click="handleAdd(formModel.keyWord)">新 增</el-button>
        <el-card class="mt-20"
                 v-if="formModel.keyWordList.length > 0">
          <div>
            <el-tag type="success"
                    style="margin-left:10px;"
                    closable
                    @close="handleClose(item)"
                    v-for="(item, index) in formModel.keyWordList"
                    :key="index">{{item}}</el-tag>
          </div>
        </el-card>
      </el-form-item>

    </el-form>
    <p align="center">
      <el-button type="info"
                 @click="modalClose">取 消</el-button>
      <el-button type="primary"
                 @click="submitForm">新 增</el-button>
    </p>
  </el-dialog>
</template>
<script>
  export default {
    name: 'knowledgeDialog', // 知识点
    props: {
      knowledgeDataObj: {
        type: Object,
        default: {}
      },
      visible: {
        type: Boolean,
        default: false
      },
      isShowDetail: {
        type: Boolean,
        default: false
      },
    },
    data () {
      return {
        title: '新增关联知识点',
        loading: false,
        imageUploadUrl: this.api.appUpgradeUpload.url,
        formModel: {
          type: 1,
          knowledge: '', // 知识点
          keyWord: '', // 关键词
          isImportant: 0, // 是否是重点知识: 1:重点 0： 不是重点
          keyWordList: [],
          knowledgeImage: [],
          knowledgeImageList: [],
          knowledgeImageUrls: '',
        },
        formRules: {
          knowledge: [{ required: true, message: '请输入知识点', trigger: 'blur' }],
          // keyWord: [{ required: true, message: '请输入知识点', trigger: 'blur' }]
        },

      }
    },
    methods: {
      modalClose () {
        this.$emit('update:visible', false); // 直接修改父组件的属性
      },
      handleAdd (val) {
        if (val === '') {
          this.$message.error('请输入关键词!');
          return;
        }
        if (!this.formModel.knowledge.includes(val)) {
          this.$message.error(`关键词【${val}】必须是重点知识点里面的!`);
          this.formModel.keyWord = '';
          return;
        }
        if (this.formModel.keyWordList.some(item => item === val)) {
          this.$message.error('不能重复添加关键词!');
          this.formModel.keyWord = '';
          return;
        }
        this.formModel.keyWord = '';
        this.formModel.keyWordList.push(val);
      },
      handleClose (val) {
        this.formModel.keyWordList.splice(this.formModel.keyWordList.indexOf(val), 1);
      },
      beforeAvatarUpload (file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isLt2M;
      },
      handlePictureCardPreview (response, file, fileList) {
        if (response.code === '200') {
          // 状态码为200时则上传成功
          let temp = [...this.formModel.knowledgeImage, ...file.response.object];
          this.formModel.knowledgeImage = temp;
          this.formModel.knowledgeImageUrls = JSON.stringify(temp);
          this.formModel.knowledgeImageList = temp.map(item => ({
            name: item,
            url: item
          }))
          this.$message.success('上传成功');
        } else {
          // 状态码不是200时上传失败 从列表中删除
          fileList.splice(fileList.indexOf(file), 1);
          this.$message.error(response.message);
        }
      },
      onremove (res, list) {
        if (res.response) {
          this.formModel.knowledgeImage = this.formModel.knowledgeImage.filter(ele => ele != res.response.object[0]);
        } else {
          this.formModel.knowledgeImage = this.formModel.knowledgeImage.filter(ele => ele != res.url);
        }
      },
      submitForm () {
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            if (this.formModel.keyWordList.length === 0) {
              this.$message.error('请输入关键词!');
              return;
            }
            this.$emit('childKnowledgeData', this.formModel);
            this.modalClose();
          }
        })
      },

    },
    created () {
      if (this.isShowDetail) {
        this.formModel = this.knowledgeDataObj;
        this.formModel.keyWord = '';
        this.formModel.knowledgeImageList = [];
        if (!this.formModel.hasOwnProperty('knowledgeImage')) {
          this.$set(this.formModel, 'knowledgeImage', []);
        }
      }
    }
  }
</script>
<style scoped lang="scss">
</style>